package com.tzinfo.tzt.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.FragmentHomeListviewAdapter3;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage;
import com.tzinfo.tzt.util.Resultmap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/12.
 */
public class MyFragment2 extends Fragment {

    private PullToRefreshListView listView;
    private Context context;
    int pagesize = 10;
    private boolean isLoadingData = false;
    int page;
    List<Resultmap> listData;
    private FragmentHomeListviewAdapter3 fragmentHomeListviewAdapter;



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = 1;
    }

    /**
     * 为Fragment加载布局时调用*
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.myfragment2_pager_list, null);
        listView = (PullToRefreshListView) view.findViewById(R.id.myFragment2__home_pager_listView);
        if (listData != null){
            fragmentHomeListviewAdapter = new FragmentHomeListviewAdapter3(context, listData);
            listView.setAdapter(fragmentHomeListviewAdapter);
        }
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout endLabels  = listView.getLoadingLayoutProxy(false,true);
        endLabels .setPullLabel("上拉加载更多");
        endLabels.setReleaseLabel("松开加载");
        endLabels.setRefreshingLabel("正在加载");
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        context,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);


                if (!isLoadingData) {
                    page = 1;
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetData().execute();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(
                        context,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                // 显示最后更新的时间
                if (!isLoadingData) {
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetData().execute();
                }
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new GetData().execute();
    }

    public class GetData extends AsyncTask<String, Void, ResultMessage> {

        protected void onPreExecute() {
            super.onPreExecute();
            if (isLoadingData) {
                this.cancel(true);
                return;
            }
            isLoadingData = true;

        }
        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumthreadList.ashx?fid=21";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                if (fragmentHomeListviewAdapter == null||page == 1) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                }
                if (listData.size()==pagesize){
                    fragmentHomeListviewAdapter = new FragmentHomeListviewAdapter3(context, listData);
                    listView.setAdapter(fragmentHomeListviewAdapter);
                }
                page++;
                fragmentHomeListviewAdapter.notifyDataSetChanged();
                listView.onRefreshComplete();
                isLoadingData = false;
            } else {
                Toast.makeText(context, result.getErrorMsg(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public void onDestroyView() {
        super.onDestroyView();
        page--;
    }


}
